﻿
//全局变量
var spPageUrl = "../ashx/sp.ashx";//后台统一页面
var pTableName = "";//增删改的，表名
var pTableIdName = "";//增删改的，表主键
var grid1ID = "";//列表的ID
var selTableinfo = "";//查询table信息 主表一定要as T 
var selFieldsinfo = "*";//查询返回的内容
var pPageCode = "";
var pPageInfoName = "-";
//权限获取
var ptoolbar = "";
//设置页面基本信息
function spsetBase(tname, tid, sinfo, sre, mgid, pcode, infoname) {
    HCUser = createObject("sys");
    pTableName = tname;
    pTableIdName = tid;
    selTableinfo = sinfo;
    selFieldsinfo = sre;
    grid1ID = mgid;
    pPageCode = pcode;
    pPageInfoName = infoname;
    ptoolbar = getToolBar();

}
function spsetBaseNoBt(tname, tid, sinfo, sre, mgid, pcode, infoname) {
    HCUser = createObject("sys");
    pTableName = tname;
    pTableIdName = tid;
    selTableinfo = sinfo;
    selFieldsinfo = sre;
    grid1ID = mgid;
    pPageCode = pcode;
    pPageInfoName = infoname;
}
//////////全局用户信息
var HCUser = null;//createObject("sys");
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}
function replaceAll2(content, oldReplace, newReplace) {
    var i;
    for (i = 0; i < content.length; i++) {
        if (content.indexOf(oldReplace) > 0) {
            content = content.replace(oldReplace, newReplace);
        }
    }
    return content;
}
//////////////////**********************主表的删查

//获取查询url 表查
//function spselUrl(spadd)
function spselUrl(spadd) {
    if (spadd != null && spadd != "undefined" && spadd.length > 0)
    { return spPageUrl + "?action=sel&tableinfo=" + selTableinfo + "&refields=" + selFieldsinfo + "&wheresp= " + escape(spadd); }
    else
        return spPageUrl + "?action=sel&tableinfo=" + selTableinfo + "&refields=" + selFieldsinfo + "";
}
//获取查询行url 
//function spselrowUrl(id)
function spselrowUrl(id) {
    return spPageUrl + "?action=GetTableObjINFO&talbename=" + pTableName + "&midname=" + pTableIdName + "&midvalue=" + id;
}
//获取DEL url
//function spdelUrl(id)
function spdelUrl(id) {
    return spPageUrl + "?action=del&tablename=" + pTableName + "&tablemidname=" + pTableIdName + "&id=" + id;
}


//查询树结构
//function sposelTreeUrl(t, r, wa)
function sposelTreeUrl(t, r, wa) {
    if (wa != null && wa != "undefined" && wa.length > 0)
    { return spPageUrl + "?action=seltree&tableinfo= " + t + "&refields= " + r + "&wheresp= " + wa; }
    else
        return spPageUrl + "?action=seltree&tableinfo= " + t + "&refields= " + r + "";
}


function sposelUrl(t, r, wa) {
    if (wa != null && wa != "undefined" && wa.length > 0)
    { return spPageUrl + "?action=sel&tableinfo=" + t + "&refields=" + r + "&wheresp= " + wa; }
    else
        return spPageUrl + "?action=sel&tableinfo=" + t + "&refields=" + r + "";
}
function spodelUrl(t, k, id) {
    return spPageUrl + "?action=del&tablename=" + t + "&tablemidname=" + k + "&id=" + id;
}

//获取查询url_sql(包含 状态+行数据)
function sposelUrlBySql(sqlinfo) {
    return spPageUrl + "?action=SqlTableGet&sqlinfo=" + escape(sqlinfo);
}
//获取查询url_sql（只有行数据）
//function sposelUrlBySqlNoState(sqlinfo)
function sposelUrlBySqlNoState(sqlinfo) {
    return spPageUrl + "?action=SqlTableGet&nostate=no&sqlinfo=" + escape(sqlinfo);
}

//获取查询url_sql(包含 状态+行数据)
function sposelUrlByF(s, t, w, g, h, o) {

    var re = spPageUrl + "?action=SqlTableGet&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    re = re.replaceAll("'", "hcdhc");
    return re;
}
//获取查询url_sql（只有行数据）
function sposelUrlByFNoState(s, t, w, g, h, o) {

    var re = spPageUrl + "?action=SqlTableGet&nostate=no&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    re = re.replaceAll("'", "hcdhc");
    return re;
}



//同步请求后台，要求后台，返回直接的json串
function spGetJson(url) {
    var re;
    $.ajax({
        type: "post",
        url: url,
        //  data: "test=" + test,
        async: false,
        success: function (data) {
            re = data;
        }
    });
    return re;
}
var toolbartext = "";
function getToolBar() {

    var toolbar = [];
    $.ajax({
        url: "../ashx/sp.ashx?action=getbuttonaccess&pagecode=" + pPageCode + "&userid=" + HCUser.HCUide,
        type: "post",
        dataType: "json",
        timeout: 5000,
        async: false,
        cache: false,
        success: function (data) {
            if (data.toolbar != undefined && data.toolbar != '') {
                $.each(data.toolbar, function (index, row) {
                    var handler = row.handler;
                    row.handler = function () { eval(handler); };
                    toolbar.push(row);
                    toolbartext += row.text + "-";
                });
            }
        }
    });
    return toolbar;
}
function setToolBar(btstring) {
    var data = $.parseJSON(btstring);
    var toolbar = [];
    if (data.toolbar != undefined && data.toolbar != '') {

        $.each(data.toolbar, function (index, row) {
            var handler = row.handler;
            row.handler = function () { eval(handler); };
            toolbar.push(row);
        });
    }
    ptoolbar = toolbar;
}
function createObject(dowhat) {

    var obj = new Object();
    //从cookie取，如果没有--或者禁用了（从后台取中取）
    if (dowhat == "reload" || hcgetCookie("HCUid") == "" || pPageCode == "index") {
        var linfo = spGetJson("../ashx/sp.ashx?action=getLogininfo&timenow=" + new Date().getTime());
        if (linfo.indexOf("会话超时") > 0) {
            parent.location.href = "../";
            //window.location.href = "../login.html";
            return;
        }
        var lobj = $.parseJSON(linfo);

        obj.HCUide = lobj[0].HCUid;
        obj.HCUname = lobj[0].HCUname;
        obj.HCUtitle = lobj[0].HCUtitle;
        obj.HCUorg = lobj[0].HCUorg;
        obj.HCUdep = lobj[0].HCUdep;
        obj.HCUorgtype = lobj[0].HCUorgtype;
        obj.HCUorgName = lobj[0].HCUorgName;
        obj.HCUdepName = lobj[0].HCUdepName;
        obj.HCUorgCode = lobj[0].HCUorgCode;

        hcsetCookie("HCUid", obj.HCUide, 1);
        hcsetCookie("HCUname", obj.HCUname, 1);
        hcsetCookie("HCUtitle", obj.HCUtitle, 1);
        hcsetCookie("HCUorg", obj.HCUorg, 1);
        hcsetCookie("HCUdep", obj.HCUdep, 1);
        hcsetCookie("HCUorgtype", obj.HCUorgtype, 1);
        hcsetCookie("HCUorgName", obj.HCUorgName, 1);
        hcsetCookie("HCUdepName", obj.HCUdepName, 1);
        hcsetCookie("HCUorgCode", obj.HCUorgCode, 1);
    }
    else {
        obj.HCUide = hcgetCookie("HCUid");
        obj.HCUname = hcgetCookie("HCUname");
        obj.HCUtitle = hcgetCookie("HCUtitle");
        obj.HCUorg = hcgetCookie("HCUorg");
        obj.HCUdep = hcgetCookie("HCUdep");
        obj.HCUorgtype = hcgetCookie("HCUorgtype");
        obj.HCUorgName = hcgetCookie("HCUorgName");
        obj.HCUdepName = hcgetCookie("HCUdepName");
        obj.HCUorgCode = hcgetCookie("HCUorgCode");
    }

    return obj;
}
//cookie
function hcsetCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";;
}
//获取cookie
function hcgetCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
//清除cookie  
function hcclearCookie(name) {
    setCookie(name, "", -1);
}



//通用标准的toolUpdate  itemEditContainer---edititemblock--itemEdit
function toolUpdate() {
    $(".validatebox-tip").remove();
    $(".validatebox-invalid").removeClass("validatebox-invalid");
    var row = $(grid1ID).datagrid("getSelections");
    if (row.length == 0) {
        $.messager.alert("提示信息", "请选择需要修改的数据！"); return;
    }
    $('#itemEdit')[0].reset();
    $("#editAction").val(CallBackCommand.Update);
    var id = row[0][pTableIdName];
    $("#id").val(id);
    {
        $.get(spselrowUrl(id) + "&timenow=" + new Date().getTime(),
            function (data) {
                var data = JSON.parse(data);
                if (data.message == JsonResult.Success) {
                    for (var i = 0; i < data.data.length; i++) {
                        var infoobj = data.data[i];
                        for (var filedname in infoobj) {
                            var gethtmlf = $("#f" + filedname);
                            if (gethtmlf && gethtmlf.length == 1) {
                                var classname = gethtmlf.attr("class");
                                if (classname == null || classname == 'undefined') {
                                    gethtmlf.val(infoobj[filedname]);
                                }
                                else if (classname.indexOf('-combobox') >= 0 || classname.indexOf('combobox-') >= 0) {
                                    gethtmlf.combobox('setValue', infoobj[filedname]);
                                }
                                else if (classname.indexOf('-combotree') >= 0) {
                                    gethtmlf.combotree('setValue', infoobj[filedname]);
                                }
                                else if (classname.indexOf('-datebox') >= 0 || classname.indexOf('-datetimebox') >= 0) {
                                    gethtmlf.datebox('setValue', infoobj[filedname]);
                                }
                                else { gethtmlf.val(infoobj[filedname]); }

                            }
                        }
                        break;
                    }
                }
                else {
                    $.messager.show({
                        title: '查找出错',
                        msg: data.data,
                        showType: 'show'
                    });
                }


            });
    }
    $('#itemEditContainer').window({ title: "修改" + pPageInfoName + "信息" });
    $("#itemEditContainer").window("open");
}
//根据行号
function toolUpdateForId(index) {
    $(".validatebox-tip").remove();
    $(".validatebox-invalid").removeClass("validatebox-invalid");
    $(grid1ID).datagrid("selectRow", index);
    var row = $(grid1ID).datagrid("getSelected");
    $('#itemEdit')[0].reset();
    $("#editAction").val(CallBackCommand.Update);
    var id = row[pTableIdName];
    toolUpdateById(id);
}
//根据ID
function toolUpdateById(id) {
    $("#id").val(id);
    {
        $.get(spselrowUrl(id) + "&timenow=" + new Date().getTime(),
            function (data) {
                var data = JSON.parse(data);
                if (data.message == JsonResult.Success) {
                    for (var i = 0; i < data.data.length; i++) {
                        var infoobj = data.data[i];
                        for (var filedname in infoobj) {
                            var gethtmlf = $("#f" + filedname);
                            if (gethtmlf && gethtmlf.length == 1) {
                                var classname = gethtmlf.attr("class");
                                if (classname == null || classname == 'undefined') {
                                    gethtmlf.val(infoobj[filedname]);
                                }
                                else if (classname.indexOf('-combobox') >= 0 || classname.indexOf('combobox-') >= 0) {
                                    gethtmlf.combobox('setValue', infoobj[filedname]);
                                }
                                else if (classname.indexOf('-combotree') >= 0) {
                                    gethtmlf.combotree('setValue', infoobj[filedname]);
                                }
                                else if (classname.indexOf('-datebox') >= 0) {
                                    gethtmlf.datebox('setValue', infoobj[filedname].split(' ')[0]);
                                }
                                else if (classname.indexOf('-datetimebox') >= 0) {
                                    gethtmlf.datebox('setValue', infoobj[filedname]);
                                }
                                else { gethtmlf.val(infoobj[filedname]); }

                            }
                        }
                        break;
                    }
                }
                else {
                    $.messager.show({
                        title: '查找出错',
                        msg: data.data,
                        showType: 'show'
                    });
                }
            });
    }
    $('#itemEditContainer').window({ title: "修改" + pPageInfoName + "信息" });
    $("#itemEditContainer").window("open");
}
//通用标准的toolDelete  inids:可指定ID，或者根据行选择处理
function toolDelete(inids) {
    var ID = "";
    if (inids) {
        ID = inids;
    }
    else {
        var rows = $(grid1ID).datagrid("getSelections");
        if (rows.length == 0) {
            $.messager.alert("提示信息", "请选择需要删除的数据！");
            return;
        }

        for (var i = 0; i < rows.length; i++) {
            ID += rows[i][pTableIdName] + ",";
        }
        ID = ID.substring(0, ID.length - 1);
    }
    $.messager.confirm("提示信息", "确定删除所选数据？", function (r) {
        if (!r) {
            $(grid1ID).datagrid("clearSelections");
            return;
        }
        $.get(spdelUrl(ID),
        function (data) {
            var data = JSON.parse(data);
            switch (data.message) {
                case JsonResult.SessionOut:
                    $.messager.alert('系统出错', ' 登录超时，请重新登录!');
                    break;
                case JsonResult.Error:
                    $.messager.alert('系统出错', data.data);
                    break;
                case JsonResult.Success:
                    $.messager.show({
                        title: '提示信息',
                        msg: data.data,
                        showType: 'show'
                    });
                    $(grid1ID).datagrid("clearSelections");
                    $(grid1ID).datagrid("load");
                    break;
            }
        });
    });

}
var toolselectObj = [];
function toolSelect() {
    var ID = "";
    {
        var rows = $(grid1ID).datagrid("getSelections");
        if (rows.length == 0) {
            $.messager.alert("提示信息", "请选择数据！");
            return;
        }

        for (var i = 0; i < rows.length; i++) {
            toolselectObj.push({
                "id": rows[i][pTableIdName], "name": rows[i]["name"]
            });
        }
        //toolselectinfoshow
        var infoshowtext = "";
        for (var p in toolselectObj) {//遍历json数组时，这么写p为索引，0,1
            infoshowtext = infoshowtext + toolselectObj[p].name + ",";
        }
    }
}

//通用标准的toolAdd  itemEditContainer---edititemblock--itemEdit
function toolAdd() {
    $(grid1ID).datagrid("clearSelections");
    $('#itemEdit')[0].reset();
    $("#editAction").val(CallBackCommand.Inseart);
    $('#itemEditContainer').window({ title: "新增" + pPageInfoName + "信息" });
    $("#itemEditContainer").window("open");
}
//通用标准的toolSubmit  itemEditContainer---edititemblock--itemEdit
function toolSubmit() {
    $("#tablename").val(pTableName);
    $("#tablemidname").val(pTableIdName);
    if (!$("#itemEdit").form('validate'))
    { return; }
    $('#itemEdit').ajaxSubmit(function (message) {
        var data = JSON.parse(message);
        if (data.message == JsonResult.Success) {
            $('#itemEditContainer').window('close');
            $.messager.show({
                title: '消息',
                msg: '信息提交成功',
                showType: 'show'
            });
            $(grid1ID).datagrid("clearSelections");
            $(grid1ID).datagrid("reload");
        }
        else {
            $.messager.show({
                title: '提交出错',
                msg: data.data,
                showType: 'show'
            });
        }
    });

}
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

//删除指定数据
function hcdodel(tablename, tablekey, tablekeyid, callback) {
    $.get(spodelUrl(tablename, tablekey, tablekeyid),
                  function (data) {
                      var data = JSON.parse(data);
                      switch (data.message) {
                          case JsonResult.SessionOut:
                              $.messager.alert('系统出错', ' 登录超时，请重新登录!');
                              callback("timeout");
                              break;
                          case JsonResult.Error:
                              $.messager.alert('系统出错', data.data);
                              callback("error");
                              break;
                          case JsonResult.Success:
                              $.messager.show({
                                  title: '提示信息',
                                  msg: data.data,
                                  showType: 'show'
                              });
                              callback("ok");
                              break;
                      }
                  });
}
//添加指定数据 fname1%fvalue1$fname2%fvalue2
function hcdoadd(tablename, fnamevalue, callback) {
    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "doadd",
            "tablename": tablename,
            "fnamevalue": fnamevalue
        },
        timeout: 9000,
        async: true,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            switch (result.message) {
                case JsonResult.Success:
                    $.messager.show({
                        title: '提示信息',
                        msg: result.data,
                        showType: 'show'
                    });
                    callback("ok");
                    break;
                case JsonResult.Error:
                    callback("error");
                    break;
                default:
                    break;
            }

        }
    });
}
//更新指定数据 fname1%fvalue1$fname2%fvalue2
function hcdoedit(tablename, key, id, fnamevalue, callback) {
    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "doedit",
            "tablename": tablename,
            "tablemidname": key,
            "id": id,
            "fnamevalue": fnamevalue
        },
        timeout: 6000,
        async: true,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            switch (result.message) {
                case JsonResult.Success:
                    $.messager.show({
                        title: '提示信息',
                        msg: result.data,
                        showType: 'show'
                    });
                    callback("ok");
                    break;
                case JsonResult.Error:
                    callback("error");
                    break;
                default:
                    break;
            }

        }
    });
}
//能用查询 select table where groupby having order callback
function hcdosels(s, t, w, g, h, o, callback) {
    $.get(sposelUrlByF(s, t, w, g, h, o) + "&timenow=" + new Date().getTime(),
            function (data) {
                callback(data);
            });
}
//能用查询 select table where groupby having order callback
function hcdosel(s, t, w, g, h, o, callback) {
    $.get(sposelUrlByFNoState(s, t, w, g, h, o) + "&timenow=" + new Date().getTime(),
            function (data) {
                callback(data);
            });
}
//通用导出
function toolExport() {
    hcdoExport("T.*", selTableinfo, "", "", "", "");
}
function hcdoExport(s, t, w, g, h, o) {
    var url = spPageUrl + "?action=Export&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    url = url.replaceAll("'", "hcdhc");
    window.open(url);
}
function toolImport(parm) {
    $('#importForm')[0].reset();
    $("#importMsg").text("");
    $("#action").val("Import");
    $('#ImportShow').window({ title: "导入信息" });
    $('#ImportShow').window('open');
}
function Import(parmf, parmv) {
    if (parmf)
        $("#importForm").attr("action", (" ../ashx/sp.ashx?" + parmf + escape(parmv)));
    if ($("#importFile").val() == "") {
        $("#importMsg").text("请选择上传文件！").addClass("waringMsg");
        return;
    }
    $("#importForm").ajaxSubmit({
        success: function (message) {
            var data = JSON.parse(message);
            if (data.message == JsonResult.Success) {
                $("#importMsg").text(data.data).addClass("successMsg");
            }
            else {
                $("#importMsg").text(data.data).addClass("waringMsg");
            }
        }
    });

}
//生成理伦唯一ID
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function NewGuid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
//调用外部winform窗体    调用的标识（方法）-主状态-信息-回调方法(必须为两个参数 funciotn (p1,p2)  没有时，为空字符串)
function callForm(callfunction, state, message, callback) {
    window.external.callform(callfunction, state, message, callback);
}


